/**
 * 将字符串中的全角字符转换为半角字符。
 * @param {String} str 
 * @returns 
 */
function DBC2SBC(str) {
    if(str == null || str == undefined) return "";
    var result = "";
    for (var i = 0; i < str.length; i++) {
        code = str.charCodeAt(i);    //获取当前字符的unicode编码
        if (code >= 65281 && code <= 65373)   //在这个unicode编码范围中的是所有的英文字母已经各种字符
        {
            var d = str.charCodeAt(i) - 65248;
            result += String.fromCharCode(d);   //把全角字符的unicode编码转换为对应半角字符的unicode码
        }
        else if (code == 12288)//空格
        {
            var d = str.charCodeAt(i) - 12288 + 32;
            result += String.fromCharCode(d);
        }
        else {
            result += str.charAt(i);
        }
    }
    return result;
}

/**
 * 去除首尾空格符
 * @param {String} str 
 * @returns 
 */
function trimStr(str) {
    if(str == null || str == undefined) return "";
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

function onbuttonclick(idStr) {
    if (typeof (wps.Enum) != "object") { // 如果没有内置枚举值
        wps.Enum = WPS_Enum
    }
    switch (idStr) {
        case "btnJoin": {
            var workbook = wps.EtApplication().ActiveWorkbook;
            var sheet = workbook.ActiveSheet;

            if (workbook == undefined) {
                alert("未设置合并条件区域！");
                return;
            }

            let s = wps.Application.Selection
            if (s.Count <= 0) {
                alert("未设置合并条件列！");
                return;
            }

            if (s.Columns.Count > 1) {
                alert("只能以单列为合并条件！");
                return;
            }

            if (sheet.UsedRange.Columns.Count <= 1) {
                alert("当前表中的数据少于两列，本操作无意义！");
                return;
            }

            var conditionColumnIndex = s.Column;
            var usedRangeColumnIndex = sheet.UsedRange.Column;
            var conditionStartRowIndex = s.Row;
            var usedRangeStartRowIndex = sheet.UsedRange.Row;
            var conditionEndRowIndex = s.Row + s.Count - 1;
            var usedRangeEndRowIndex = usedRangeStartRowIndex + sheet.UsedRange.Rows.Count - 1;

            var conditionArrayColumnIndex = conditionColumnIndex - usedRangeColumnIndex;
            var conditionArrayStartRowIndex = conditionStartRowIndex - usedRangeStartRowIndex;
            var conditionArrayEndRowIndex = conditionEndRowIndex - usedRangeStartRowIndex;

            if (conditionArrayColumnIndex < 0 || conditionColumnIndex >= usedRangeColumnIndex + sheet.UsedRange.Columns.Count - 1) {
                alert("指定条件列不在有效区域内！");
                return;
            }

            var inUsedRange = false;
            if (conditionStartRowIndex >= usedRangeStartRowIndex && conditionEndRowIndex <= usedRangeEndRowIndex) {
                inUsedRange = true;
            }

            if (inUsedRange == false) {
                alert("指定条件列不在有效数据区域内！");
                return;
            }

            var srcArray = sheet.UsedRange.Value2;

            var resultArray = [];
            var preConditionValue = null;
            for (let i = conditionArrayStartRowIndex; i <= conditionArrayEndRowIndex; i++) {
                var row = srcArray[i];
                var condition = row[conditionArrayColumnIndex];
                var conditionValue = trimStr(DBC2SBC(condition.toString()));
                if (preConditionValue == null) {
                    preConditionValue = conditionValue;
                    resultArray.push(row);
                    continue;
                }

                if (conditionValue == preConditionValue) {
                    // 合并上去
                    var lastResultRow = resultArray[resultArray.length - 1];
                    for (let j = conditionArrayColumnIndex + 1; j < row.length; j++) {
                        var cellValue = row[j];
                        if (cellValue == undefined || cellValue == null || cellValue.length <= 0) {
                            lastResultRow.push("");
                        }
                        else {
                            lastResultRow.push(cellValue.toString());
                        }
                    }
                    // 不变：preConditionValue = conditionValue;
                } else {
                    // 不合并，原样推入结果数组
                    var newRowArray = [];
                    for(let j = 0; j < row.length; j++){
                        var cellValue = row[j];
                        if (cellValue == undefined || cellValue == null || cellValue.length <= 0) {
                            newRowArray.push("");
                        }
                        else {
                            newRowArray.push(cellValue.toString());
                        }
                    }
                    resultArray.push(newRowArray);
                    preConditionValue = conditionValue;
                }
            }

            var maxColumns = -1;
            for (let i = 0; i < resultArray.length; i++) {
                var resultRow = resultArray[i];
                if (resultRow.length > maxColumns) {
                    maxColumns = resultRow.length;
                }
            }
            var resultRowsCount = resultArray.length;

            // 找到的数据放在新表中
            var newSheet = workbook.Sheets.Add();
            newSheet.Cells.NumberFormatLocal = "@";   // 必须设置为文本格式

            newSheet.Range(newSheet.Cells.Item(1, 1), newSheet.Cells.Item(1, maxColumns)).Value2 = "字段";
            newSheet.Range(newSheet.Cells.Item(1, conditionArrayColumnIndex + 1), newSheet.Cells.Item(1, conditionArrayColumnIndex + 1)).Value2 = "【条件】";

            var titleRng = newSheet.Range(newSheet.Cells.Item(1, 1), newSheet.Cells.Item(1, maxColumns));
            titleRng.Interior.Pattern = 1;  //xlPatternSolid;
            titleRng.Interior.ThemeColor = 6;
            titleRng.Interior.TintAndShade = 0.8;
            titleRng.Interior.PatternColorIndex = -4105;

            var conditionRng = newSheet.Range(newSheet.Cells.Item(1, conditionArrayColumnIndex + 1), newSheet.Cells.Item(resultArray.length + 1, conditionArrayColumnIndex + 1));
            conditionRng.Interior.Pattern = 1;
            conditionRng.Interior.Color = 65535;
            conditionRng.Interior.TintAndShade = 0;
            conditionRng.Font.Color = 255;
            conditionRng.Font.TintAndShade = 0;

            if(resultArray.length <= 0){
                alert("无有效数据！")
                return;
            }

            // 数组第一行，如果不给空值加上点什么，将数组赋予某个 Range 时，空值部分所有行都不能显示值！！！
            // 这里加个空字符串！！！
            var emptyOfFstLine = maxColumns - resultArray[0].length;
            for(let i = 0; i < emptyOfFstLine; i++){
                resultArray[0].push("")
            }

            newSheet.Range(newSheet.Cells.Item(2, 1), newSheet.Cells.Item(resultRowsCount + 1, maxColumns)).Value2 = resultArray;
            // 留下首行粘贴标题
            newSheet.UsedRange.Columns.AutoFit();
            break;
        }
    }
}
